package com.mtw.bbs.article.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mtw.bbs.article.pojo.entity.TopicType;
import com.mtw.bbs.article.pojo.form.TopicTypeForm;
import com.mtw.bbs.article.service.TopicTypeService;
import com.mtw.bbs.common.core.exception.BusinessException;
import com.mtw.bbs.common.core.vo.Result;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;

/**
 * 话题分类接口层
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("admin/topicType")
public class AdminTopicTypeController {


    private final TopicTypeService topicTypeService;



    /**
     * 分页获取话题分类
     *
     * @param page   当前页
     * @param size   分页大小
     * @param name   名称
     */
    @GetMapping("/page")
    public Result getTypeVoPage(
            @RequestParam(name = "page") int page,
            @RequestParam(name = "size") int size,
            @RequestParam(name = "name", required = false) String name) {

        LambdaQueryWrapper<TopicType> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(name), TopicType::getName, name);
        lqw.orderByAsc(TopicType::getSort);
        lqw.orderByDesc(TopicType::getCreatedDate);
        Page<TopicType> typePage = topicTypeService.page(new Page<>(page, size), lqw);
        return Result.success(typePage);
    }




    /**
     * 保存分类信息
     */
    @PostMapping("/save")
    public Result save(@RequestBody TopicTypeForm form) {

        boolean saved = topicTypeService.saveTopicType(form);
        return saved ? Result.success() : Result.fail("保存失败");
    }


    /**
     * 修改分类信息
     */
    @PutMapping("/update")
    public Result update(@RequestBody TopicTypeForm form) {

        boolean updated = topicTypeService.updateTopicType(form);
        return updated ? Result.success() : Result.fail("修改失败");
    }


    /**
     * 根据id删除分类
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") String id) {

        try {
            boolean deleted = topicTypeService.deleteTopicType(id);
            return deleted ? Result.success() : Result.fail("删除失败");
        }catch (BusinessException e){
            return Result.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "删除分类", notes = "根据ids来指定删除对象")
    @DeleteMapping(value = "/delete")
    public Result delete(@RequestBody String[] ids) {

        try {
            boolean deleted = topicTypeService.deleteTopicType(Arrays.asList(ids));
            return deleted ? Result.success() : Result.fail("删除失败");
        }catch (BusinessException e){
            return Result.fail(e.getMessage());
        }
    }

}
